package com.nopay.dxdwphone.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

import com.azhon.basic.eventbus.MessageEvent;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import com.nopay.dxdwphone.Constants;
import com.nopay.dxdwphone.R;

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {
	
    private IWXAPI api;

    private TextView mTvPayResult;
	private int mPayResultCode;

    private static final String[] PAY_RESULT_MSG = {"支付成功", "支付失败", "用户取消"};
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pay_result);
		EventBus.getDefault().register(this);

    	api = WXAPIFactory.createWXAPI(this, Constants.WX_APP_KEY);
        api.handleIntent(getIntent(), this);

		mTvPayResult = findViewById(R.id.tv_pay_result);
		mTvPayResult.setText(PAY_RESULT_MSG[Math.abs(mPayResultCode)]);

		findViewById(R.id.tv_pay_back).setOnClickListener(view -> {
			// TODO 支付返回
			EventBus.getDefault().post(new MessageEvent(MessageEvent.TYPE_WE_PAY_RESULT, mPayResultCode, PAY_RESULT_MSG[Math.abs(mPayResultCode)]));
			finish();
		});
    }

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
        api.handleIntent(intent, this);
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onDataEvent(MessageEvent msg) {

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		EventBus.getDefault().unregister(this);
	}

	@Override
	public void onReq(BaseReq req) {
	}

	@Override
	public void onResp(BaseResp resp) {
		if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
			mPayResultCode = resp.errCode;
		}
	}
}